<?php

/**
 * System core file
 *
 * @author coder_
 */

class _Core
{
    private static $instance;

    private $startController;
    private $requestMethod;
    /**
     * Prevent direct object creation
     */
    private function __construct()
    {
        getModules()->initialize();
    }

    /**
     * Prevent creation by cloning
     *
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * Return the single instance of the core
     *
     * @static
     * @return
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     * Starting point for system execution
     *
     * @return void
     */
    public function startExecution()
    {
        $this->processPreFilters();
        $this->processController();
        $this->processPostFilters();
    }

    private function processPreFilters()
    {
        // TODO do pre filters processing
    }

    private function processController()
    {
        $controller = getModules()->Request->findController();

        if(empty($controller))
        {
            // TODO show 404 not found error page
            println('no page');
            return;
        }

        if(!$this->loadController($controller))
        {
            // TODO show 500 internal error page
            println('no controller');
            return;
        }

        if(!$this->checkController())
        {
            // TODO show 500 internal error page || silently exit
            println('no method');
            return;
        }

        ob_start();

        call_user_func(array($this->startController, $this->requestMethod));

        $output = ob_get_clean();

        echo $output;
    }

    private function processPostFilters()
    {
        // TODO do post filters processing
    }

    private function setStartController($controller)
    {
        $this->startController = new $controller();
    }

    private function loadController($controller)
    {
        $controllerFile = CONTROLLERS . '/' . $controller . '.php';
        if(file_exists($controllerFile))
        {
            require_once($controllerFile);
            $this->setStartController(ucwords($controller));

            return true;
        } else {
            return false;
        }
    }

    private function checkController()
    {
        $requestMethod = strtolower(getModules()->Request->getRequestMethod());
        $this->requestMethod = $requestMethod;
        if(method_exists($this->startController, $requestMethod))
        {
            return true;
        } else {
            return false;
        }
    }
}